package com.itheima.sh.user.service.impl;


import com.itheima.sh.pojo.Order;
import com.itheima.sh.pojo.User;
import com.itheima.sh.request.dtos.UserOrderDTO;
import com.itheima.sh.response.vos.OrderVo;
import com.itheima.sh.response.vos.UserOrderVo;
import com.itheima.sh.user.feign.IndentApi;
import com.itheima.sh.user.mapper.UserMapper;
import com.itheima.sh.user.service.UserService;
import com.mysql.jdbc.StringUtils;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.StringUtil;

import javax.tools.Tool;
import java.util.*;

@Service
@Transactional
public class UserServiceimpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Autowired
    IndentApi indentApi;

    @Autowired
    Mapper mapper;

    @Override
    public List<User> findUserById(String username) {
        //创建条件查询对象
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();

        if(StringUtil.isEmpty(username)){
            throw new RuntimeException("参数不能为空");
        }
        criteria.andEqualTo("username",username);
        List<User> users = userMapper.selectByExample(example);

        return users;
    }

    @Override
    public UserOrderVo findOrderByUserId(UserOrderDTO username) {
        if (StringUtil.isEmpty(username.getUsername())){
            throw new RuntimeException("参数不能为空");
        }
        User user = userMapper.selectByPrimaryKey(username.getUsername());
        // JDK 对对象非空判断做的规范
        Optional<User> optionalUser = Optional.ofNullable(user);
        if (!optionalUser.isPresent()){
            throw new RuntimeException("没有查询到此用户");
        }
        //根据用户订单远程调用
        List<Order> orderList = indentApi.findOrderByUserId(username.getUsername());
        UserOrderVo userOrderVo = new UserOrderVo();
        // 原对象中属性名称和目标对象的属性名称保存一致才可以封装
        mapper.map(optionalUser.get(),userOrderVo);

        List<OrderVo> orderVoList = new ArrayList<>();
        //遍历list集合
        for (Order order:orderList) {
            OrderVo orderVo = new OrderVo();
            this.mapper.map(order,orderVo);
            orderVoList.add(orderVo);
        }
        userOrderVo.setOrders(orderVoList);

        return userOrderVo;
    }


}
